<template>
  <el-dialog
    v-model="visible"
    :title="`用户管理 - ${role?.name}`"
    width="800px"
    :close-on-click-modal="false"
  >
    <div class="role-users-dialog" v-loading="loading">
      <!-- 统计信息和操作按钮 -->
      <div class="stats-section">
        <div class="stats-header">
          <el-alert
            :title="`该角色共关联 ${roleUsers.count} 个用户`"
            type="info"
            :closable="false"
            show-icon
          />
          <div class="stats-actions">
            <el-button type="primary" size="small" @click="showAddUserDialog = true">
              <el-icon><Plus /></el-icon>
              添加用户
            </el-button>
            <el-button
              v-if="selectedUsers.length > 0"
              type="danger"
              size="small"
              @click="batchRemoveUsers"
            >
              <el-icon><Delete /></el-icon>
              移除选中 ({{ selectedUsers.length }})
            </el-button>
          </div>
        </div>
      </div>

      <!-- 用户列表 -->
      <div class="users-section">
        <el-table
          :data="roleUsers.users"
          style="width: 100%"
          max-height="400"
          empty-text="该角色暂无关联用户"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="username" label="用户名" width="120">
            <template #default="{ row }">
              <UserDisplay :user="row" />
            </template>
          </el-table-column>
          <el-table-column prop="email" label="邮箱" />
          <el-table-column label="姓名" width="100">
            <template #default="{ row }">
              {{ getFullName(row) }}
            </template>
          </el-table-column>
          <el-table-column prop="is_active" label="状态" width="80">
            <template #default="{ row }">
              <el-tag :type="row.is_active ? 'success' : 'danger'" size="small">
                {{ row.is_active ? '激活' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="last_login" label="最后登录" width="150">
            <template #default="{ row }">
              {{ row.last_login ? formatDateTime(row.last_login) : '从未登录' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="{ row }">
              <el-button
                size="small"
                type="primary"
                link
                @click="viewUserDetail(row)"
              >
                查看详情
              </el-button>
              <el-button
                size="small"
                type="danger"
                link
                @click="removeUser(row)"
              >
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 删除警告 -->
      <div v-if="showDeleteWarning" class="warning-section">
        <el-alert
          title="删除角色影响分析"
          type="warning"
          :closable="false"
          show-icon
        >
          <template #default>
            <p>删除该角色将影响以上 {{ roleUsers.count }} 个用户，他们将失去以下权限：</p>
            <ul class="permission-list">
              <li v-for="permission in rolePermissions" :key="permission.id">
                {{ permission.name }} ({{ permission.access_level === 'write' ? '读写' : '只读' }})
              </li>
            </ul>
            <p><strong>建议：</strong>在删除角色前，请先为这些用户分配其他合适的角色。</p>
          </template>
        </el-alert>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">关闭</el-button>
        <el-button
          v-if="showDeleteWarning"
          type="danger"
          @click="confirmDelete"
        >
          仍要删除角色
        </el-button>
      </div>
    </template>

    <!-- 添加用户对话框 -->
    <el-dialog
      v-model="showAddUserDialog"
      title="添加用户到角色"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="add-user-dialog">
        <!-- 搜索框 -->
        <div class="search-section">
          <el-input
            v-model="userSearchKeyword"
            placeholder="搜索用户名或邮箱"
            @input="searchUsers"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>

        <!-- 可添加的用户列表 -->
        <div class="available-users">
          <el-table
            :data="availableUsers"
            style="width: 100%"
            max-height="300"
            @selection-change="handleAvailableUsersSelection"
            v-loading="loadingUsers"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="username" label="用户名" width="120">
              <template #default="{ row }">
                <UserDisplay :user="row" />
              </template>
            </el-table-column>
            <el-table-column prop="email" label="邮箱" />
            <el-table-column label="姓名" width="100">
              <template #default="{ row }">
                {{ getFullName(row) }}
              </template>
            </el-table-column>
            <el-table-column prop="is_active" label="状态" width="80">
              <template #default="{ row }">
                <el-tag :type="row.is_active ? 'success' : 'danger'" size="small">
                  {{ row.is_active ? '激活' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showAddUserDialog = false">取消</el-button>
          <el-button
            type="primary"
            @click="confirmAddUsers"
            :disabled="selectedAvailableUsers.length === 0"
            :loading="addingUsers"
          >
            添加选中用户 ({{ selectedAvailableUsers.length }})
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, Search } from '@element-plus/icons-vue'
import { userManagementAPI } from '@/api/userManagement'
import UserDisplay from '@/components/UserDisplay.vue'
import { getFullName } from '@/utils/userUtils'

// Props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  role: {
    type: Object,
    default: null
  },
  showDeleteWarning: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['update:modelValue', 'delete-confirmed', 'view-user'])

// 响应式数据
const loading = ref(false)
const loadingUsers = ref(false)
const addingUsers = ref(false)
const roleUsers = ref({ users: [], count: 0 })
const rolePermissions = ref([])

// 用户管理相关数据
const showAddUserDialog = ref(false)
const userSearchKeyword = ref('')
const availableUsers = ref([])
const selectedUsers = ref([])
const selectedAvailableUsers = ref([])

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 方法
const loadRoleUsers = async () => {
  if (!props.role) return
  
  loading.value = true
  try {
    const [usersResponse, permissionsResponse] = await Promise.all([
      userManagementAPI.getRoleUsers(props.role.id),
      userManagementAPI.getRolePermissionsDetail(props.role.id)
    ])
    
    roleUsers.value = usersResponse
    rolePermissions.value = permissionsResponse.role_permissions
    
  } catch (error) {
    console.error('加载角色用户失败:', error)
    ElMessage.error('加载角色用户失败')
  } finally {
    loading.value = false
  }
}

const viewUserDetail = (user) => {
  emit('view-user', user)
}

const confirmDelete = () => {
  emit('delete-confirmed', props.role)
  visible.value = false
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 新增的用户管理方法
const handleSelectionChange = (selection) => {
  selectedUsers.value = selection
}

const handleAvailableUsersSelection = (selection) => {
  selectedAvailableUsers.value = selection
}

const searchUsers = async () => {
  if (!props.role) return

  loadingUsers.value = true
  try {
    // 获取所有用户
    const allUsersResponse = await userManagementAPI.getUsers({
      search: userSearchKeyword.value
    })

    // 过滤掉已经关联的用户
    const currentUserIds = roleUsers.value.users.map(user => user.id)
    availableUsers.value = (allUsersResponse.results || allUsersResponse).filter(
      user => !currentUserIds.includes(user.id)
    )

  } catch (error) {
    console.error('搜索用户失败:', error)
    ElMessage.error('搜索用户失败')
  } finally {
    loadingUsers.value = false
  }
}

const confirmAddUsers = async () => {
  if (selectedAvailableUsers.value.length === 0) return

  addingUsers.value = true
  try {
    // 为选中的用户分配角色
    for (const user of selectedAvailableUsers.value) {
      await userManagementAPI.updateUser(user.id, {
        ...user,
        roles: [...(user.roles || []), props.role.id]
      })
    }

    ElMessage.success(`成功添加 ${selectedAvailableUsers.value.length} 个用户`)
    showAddUserDialog.value = false
    selectedAvailableUsers.value = []
    userSearchKeyword.value = ''
    availableUsers.value = []

    // 重新加载角色用户
    await loadRoleUsers()

  } catch (error) {
    console.error('添加用户失败:', error)
    ElMessage.error('添加用户失败')
  } finally {
    addingUsers.value = false
  }
}

const removeUser = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定要将用户 "${user.username}" 从角色 "${props.role.name}" 中移除吗？`,
      '确认移除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 从用户的角色列表中移除当前角色
    const updatedRoles = (user.roles || []).filter(roleId => roleId !== props.role.id)
    await userManagementAPI.updateUser(user.id, {
      ...user,
      roles: updatedRoles
    })

    ElMessage.success('用户移除成功')
    await loadRoleUsers()

  } catch (error) {
    if (error !== 'cancel') {
      console.error('移除用户失败:', error)
      ElMessage.error('移除用户失败')
    }
  }
}

const batchRemoveUsers = async () => {
  if (selectedUsers.value.length === 0) return

  try {
    await ElMessageBox.confirm(
      `确定要将选中的 ${selectedUsers.value.length} 个用户从角色 "${props.role.name}" 中移除吗？`,
      '确认批量移除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 批量移除用户
    for (const user of selectedUsers.value) {
      const updatedRoles = (user.roles || []).filter(roleId => roleId !== props.role.id)
      await userManagementAPI.updateUser(user.id, {
        ...user,
        roles: updatedRoles
      })
    }

    ElMessage.success(`成功移除 ${selectedUsers.value.length} 个用户`)
    selectedUsers.value = []
    await loadRoleUsers()

  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量移除用户失败:', error)
      ElMessage.error('批量移除用户失败')
    }
  }
}

// 监听角色变化
watch(() => props.role, (newRole) => {
  if (newRole && visible.value) {
    loadRoleUsers()
  }
}, { immediate: true })

watch(visible, (newVisible) => {
  if (newVisible && props.role) {
    loadRoleUsers()
  }
})

watch(showAddUserDialog, (newVisible) => {
  if (newVisible) {
    searchUsers()
  }
})
</script>

<style scoped>
.role-users-dialog {
  max-height: 500px;
}

.stats-section {
  margin-bottom: 20px;
}

.stats-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 15px;
}

.stats-actions {
  display: flex;
  gap: 8px;
  flex-shrink: 0;
}

.add-user-dialog {
  padding: 10px 0;
}

.search-section {
  margin-bottom: 15px;
}

.available-users {
  margin-top: 15px;
}

.users-section {
  margin-bottom: 20px;
}

.warning-section {
  margin-top: 20px;
}

.permission-list {
  margin: 10px 0;
  padding-left: 20px;
}

.permission-list li {
  margin: 5px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
